package jjn.carl.string;

/**
 * @author Jiang Jining
 * @since 2023-07-05 23:33
 */
public class LeetCode151 {
    public String reverseWords(String s) {
        // 每个单词的开始和结束索引（左闭右开）
        int start, end;
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ') {
                //跳过空格
                continue;
            }
            //找到结束索引
            end = i + 1;
            while (i >= 0 && s.charAt(i) != ' ') {
                //跳过空格
                i--;
            }
            //找到开始索引
            start = i + 1;
            for (int j = start; j < end; j++) {
                //将每个单词按开始结束索引赋值到StringBuilder
                sb.append(s.charAt(j));
            }
            //加上单词间的空格
            sb.append(' ');
        }
        //删掉最后一个多余的空格
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    
    public static void main(String[] args) {
        System.out.println("new LeetCode151().reverseWords(\"the sky is blue\") = " + new LeetCode151().reverseWords("the sky is blue"));
        System.out.println("new LeetCode151().reverseWords(\"  hello world  \") = " + new LeetCode151().reverseWords("  hello world  "));
        System.out.println("new LeetCode151().reverseWords(\"a good   example\") = " + new LeetCode151().reverseWords("a good   example"));
    }
}
